#ifndef _TCP_SERVER_H_
#define _TCP_SERVER_H_
#include <iostream>
#include <cstdint>
#include <functional>
#include <vector>
#include<netinet/in.h>    
#include<arpa/inet.h>  
#include<sys/socket.h>    
#include<unistd.h>    

#include<stdio.h>    
#include<string.h>    

#include<event.h>    
#include<event2/listener.h>    
#include<event2/bufferevent.h>    

using StatusCB = std::function<void (int)>;
// 接收到数据的回调函数.
using ReadMsgCB = std::function<void (char * const, uint32_t)>;

class CTcpServer
{
public:
    CTcpServer(const uint16_t &listenPort, const std::string &ip="0.0.0.0");
    ~CTcpServer();

    bool SetReadMsgCB(ReadMsgCB msgCB);
    bool SetStatusCB(StatusCB statusCB);

    bool SendMsg(const std::string &msg);

    bool Run();

private:
    friend void listener_cb(evconnlistener *listener, evutil_socket_t fd,
                            sockaddr *sock, int socklen, void *arg);

    friend void socket_read_cb(bufferevent *bev, void *arg);

    friend void socket_event_cb(bufferevent *bev, short events, void *arg);

private:
    uint16_t _listenPort;
    std::string _listenIp;
    event_base *_pBase = nullptr;
    evconnlistener *_pListener = nullptr;
    ReadMsgCB _readMsgCB = nullptr;
    StatusCB _statusCB = nullptr;

    struct Tcb {
        bufferevent *pBev;
        std::string clientIp;
        uint16_t clientPort;        
    };
    std::vector<Tcb> _clients;
    
};


#endif // _TCP_SERVER_H_ 